//app.js
var util = require('utils/util.js')
var utilMd5 = require('utils/md5.js');
var isRunning = false;
App({

  globalData: {
    userInfo: null,
    imgDomain: 'https://api.artart.cn/wechat',
    isFromLaunch: true,
    verson:'v2.1.3'
  },

  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var that = this;
    //var logs = wx.getStorageSync('logs') || []
    //logs.unshift(Date.now())
    //wx.setStorageSync('logs', logs)
    wx.clearStorageSync();
    //登录并获取当前用户信息
    //that.LoginUserInfo();
  },
  //登录并获取当前用户信息
  LoginUserInfo: function (cb, inviteuid = 0) {
    if (isRunning) {
      return;
    }
    isRunning = true;
    console.log("LoginUserInfo ");
    var that = this
    if(typeof inviteuid == 'undefined' || !inviteuid || inviteuid <= 0) {
      inviteuid = 0;
    }
    //先判断缓存中有无数据
    var userInfo = wx.getStorageSync('userInfo');    
    if (userInfo) {
      console.log("LoginUserInfo return StorageSync");
      that.globalData.userInfo = userInfo;
      typeof cb == "function" && cb(this.globalData.userInfo)
      isRunning = false;
    } else {
      //调用微信登录接口  
      wx.login({
        success: function (e) {
          console.log("LoginUserInfo wx.login success");
          wx.getUserInfo({
            success: function (res) {
              isRunning = false;
              console.log("LoginUserInfo wx.getUserInfo success:", res);
              var js_code = e.code;
              //艺术家小程序登录地址
              var loginUrl = 'https://api.artart.cn/index.php?app=w3g&mod=Public&act=loginWechatSmall';
              wx.request({
                url: loginUrl,
                data: {
                  code: js_code,
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  inviteuid : inviteuid
                },
                method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                // header: {}, // 设置请求的 header
                success: function (response) {
                  console.log("LoginUserInfo wx.request success：", response);
                  if (response.data.status == 1) {
                    //登录成功，存储信息    
                    // wx.showToast({
                    //   title: '授权登录成功返回： ' + JSON.stringify(response.data.data),
                    // })                
                    that.globalData.userInfo = response.data.data;
                    wx.setStorageSync('userInfo', response.data.data);
                    console.log(that.globalData);
                    typeof cb == "function" && cb(that.globalData.userInfo)
                  } else {
                    wx.showToast({
                      title: response.data.message,
                      icon: 'error',
                      duration: 2000
                    })
                  }
                },
                fail: function (e) {
                  // fail
                  console.log("LoginUserInfo wx.request fail:", e);
                }
              })
            },
          
            fail: function(e) {
              console.log("wx getUserInfo fail: ");
              console.log(e);
              typeof cb == "function" && cb(-1);
            }
          })
        },
        fail: function (e) {
          isRunning = false;
          console.log(e);
        }
      });
      isRunning = false;
    }
  },

  reAuthorize: function (cb){
    // var that = this;
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          console.log("reAuthorize success:", res);
          typeof cb == "function" && cb(1);
        } else {
          console.log("reAuthorize fail:", res);
          typeof cb == "function" && cb(-1);
        }
      },
      // fail:function(res){
      //   console.log("reAuthorize fail:", res);
      //   typeof cb == "function" && cb(-1);
      // },
      // complete: function (res) {
      //   if (res.authSetting["scope.userInfo"]) {
      //     console.log("reAuthorize success:", res);
      //     typeof cb == "function" && cb(1);
      //   } else {
      //     console.log("reAuthorize fail:", res);
      //     typeof cb == "function" && cb(-1);
      //   }
      // }
    }) 
  },

  //获取某个用户信息
  GetUserInfo: function(uid, cb){
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "userinfo",
        "uid": uid
      },
      success: function (responseData) {
        var res = responseData.data
        //格式化图片
        if(res.photo){
          res.photosData = res.photo.split(',');
        } else {
          // res.photosData = [];
        }
        //格式化视频
        if(res.video){
          res.videosData = res.video.split(',');
        }
        typeof cb == "function" && cb(res)
      }
    });
  },

  //保存 模版消息 的推送 formid
  saveFormId : function (formid) {
    this.LoginUserInfo(function (res) {
      if(res == -1){//授权失败 无法上传formId
        return;
      }

      var privateKey = utilMd5.hexMD5(res.uid + 'addformid' + res.token);
      util.api({
        method: "POST",
        data: {
          "privatekey": privateKey,
          "ac": "addformid",
          "uid": res.uid,
          "formid": formid
        },
        success: function (responseData) {
          var res = responseData.data;
          console.log("save form id :", res);
        }
      });

    });
  },

  
  //页面分享
  sharePage: function(content, uid) {
    if(content) {
      return content;
    } else {
      return {
        // title: '艺术通讯录',
        title: '限时免费加入万人艺术社群，还有红包抢到手软',
        path: '/pages/mail-list/mail-list?inviteuid='+uid
      };
    }
  },
  //消息提示
  dialog: function(title, icon, cb) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 2000
    });
    setTimeout(function(){
      wx.hideToast()
    }, icon =='success' ? 2000:1000)
    typeof cb == "function" && cb()
  },

  //消息提示
  dialogToast: function (title, icon, cb) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: 1500
    });
    setTimeout(function () {
      wx.hideToast(),
      typeof cb == "function" && cb()
    }, 1500)
    
  },

  debug: true
})